package com.btt.ff14Tools.common;

import com.btt.ff14Tools.entity.HuanKa;
import com.csvreader.CsvReader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import java.io.*;
import java.nio.charset.Charset;
import java.util.*;

@Component
//@Order(1)
@Slf4j
public class DataLoader implements ApplicationRunner {
    private static String huankaFilePath;
    private static String huankaObtainedFilePath;// = "data/HUANKA_OBTAINED";

    private static List<HuanKa> huankaList = new ArrayList<>();
    private static List<String> huanKaObtainedList = new ArrayList<>();
    private static Set<String> huanKaObtainedSet = new HashSet<>();

    @Value("${resources.huanka.data:data/HUANKA_DATA.csv}")
    public void setHuankaFilePath(String str){
        DataLoader.huankaFilePath = str;
    }

    @Value("${resources.huanka.obtainedLog:data/HUANKA_OBTAINED}")
    public void setHuankaObtainedFilePath(String str) throws IOException {
        DataLoader.huankaObtainedFilePath = str;
        this.verifyFile(DataLoader.huankaObtainedFilePath);
    }

    public static List<HuanKa> getHuankaList(){
        return huankaList;
    }
    public static List<String> getHuanKaObtainedList(){
        return huanKaObtainedList;
    }
    public static Set<String> getHuanKaObtainedSet(){
        return huanKaObtainedSet;
    }

    @Override
    public void run(ApplicationArguments args) throws Exception{
        loadHuankaData();
    }

    private static void verifyFile(String path) throws IOException {
        File file = new File(path);
        if(!file.exists()){
            file.createNewFile();
        }
    }

    private static void loadHuankaData() {
        log.info("幻卡数据路径：{}", huankaFilePath);
        log.info("已获取幻卡数据log路径: {}", huankaObtainedFilePath);
        //读取已获得幻卡编号列表
        try {
            FileReader fileReader = new FileReader(huankaObtainedFilePath);
            BufferedReader bf = new BufferedReader(fileReader);
            String str = "";
            if(( str = bf.readLine() ) != null) {
                huanKaObtainedList = Arrays.asList(str.split(","));
                huanKaObtainedSet = new HashSet<>(huanKaObtainedList);
                log.info("已获取的幻卡编号为：{}", huanKaObtainedList.toString());
            }

            bf.close();
            fileReader.close();
        } catch (Exception e) {
            log.info("加载已获取幻卡数据失败");
        }

        //读取幻卡数据
        CsvReader reader = null;
        try {
            reader = new CsvReader(huankaFilePath, '，', Charset.forName("GBK"));
            reader.readHeaders();
            while (reader.readRecord()){
                List<String> line = Arrays.asList(reader.getRawRecord().split("，"));
                HuanKa huanKa = new HuanKa();
                huanKa.setIndex(Integer.valueOf(line.get(0)));
                huanKa.setSIndex(line.get(2));
                if(huanKaObtainedSet.contains(line.get(0))){
                    huanKa.setIsObtained(true);
                }else{
                    huanKa.setIsObtained(false);
                }
                huanKa.setDataPatch(line.get(1));
                huanKa.setCardName(line.get(3));
                huanKa.setImgUrlS(line.get(4));
                huanKa.setImgUrlB(line.get(5));
                huanKa.setRare(line.get(6));
                huanKa.setOrg(line.get(7));
                huanKa.setTop(Integer.valueOf(line.get(8)));
                huanKa.setRight(Integer.valueOf(line.get(9)));
                huanKa.setDown(Integer.valueOf(line.get(10)));
                huanKa.setLeft(Integer.valueOf(line.get(11)));
                if(line.size()>12) {
                    huanKa.setMethods(line.get(12));
                }else{
                    huanKa.setMethods("");
                }
                huankaList.add(huanKa);
            }
            log.info("已导入幻卡数据，共{}张", huankaList.size());
        } catch (Exception e) {
            log.error("读取幻卡数据报错，{}", e);
        } finally {
            if (null != reader){
                reader.close();
            }
        }
    }

    public static void rewriteSet(Set<String> strSet){
        try {
            BufferedWriter writer = new BufferedWriter(new FileWriter(huankaObtainedFilePath));
            System.out.println(strSet.toString());
            StringBuilder sb = new StringBuilder();
            for (String str:strSet){
                sb.append(str);
                sb.append(",");
            }
            writer.write(sb.toString());

            writer.close();
        }catch (IOException e){
            log.error("幻卡获取记录写失败");
        }
    }
}
